package com.ulewo.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;

public class AESSecurity {

    private static final Logger logger = LoggerFactory.getLogger(AESSecurity.class);

    /**
     * 加密
     * @param key   KEY
     * @param input 输入字符串
     * @return
     */
    public static String encrypt(String key, String input) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            logger.error("[AES加密]加密异常：", e);
            return null;
        }
        return new String(Base64.encodeBase64(crypted));
    }

    /**
     * 解密
     * @param key   KEY
     * @param input 输入字符串
     * @return
     */
    public static String decrypt(String key, String input) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decodeBase64(input.getBytes()));
            output = cipher.doFinal(base64Decode(input));

        } catch (Exception e) {
            logger.error("[AES解密]解密异常：", e);
            return null;
        }
        return new String(output);
    }

    /**
     * Base64加密
     * @param s
     * @return
     */
    public static String base64Encode(byte[] s) {
        if (s == null)
            return null;
        return Base64.encodeBase64String(s);
    }

    /**
     * Base64解密
     * @param s
     * @return
     * @exception IOException
     */
    public static byte[] base64Decode(String s) throws IOException {
        if (s == null) {
            return null;
        }
        return Base64.decodeBase64(s);
    }
}